package com.youku.expression;

import java.util.LinkedList;
import java.util.List;

public class Expression {

	private String expressionString;

	private String value;

	private List<ExpressionHandler> handlers;

	private Position position;

	public Expression(Position position, String expressionString) {
		this.expressionString = expressionString;
		this.position = position;
		this.handlers = new LinkedList<>();
		this.handlers.add(new ResultExpressionHandler(position));
		this.handlers.add(new NormalExpressionHandler(position));
	}

	public String get() {

		if (value == null) {
			for (ExpressionHandler handler : handlers) {
				// 按照放置的次序，先执行resultExpression解释，再执行normalExpression解释
				expressionString = handler.parse(expressionString);
			}
			value = expressionString;
		}
		return value;
	}

	public void setPosition(Position position) {
		this.position = position;
		handlers.clear();
		handlers.add(new ResultExpressionHandler(position));
		handlers.add(new NormalExpressionHandler(position));
	}

	public String getExpressionString() {
		return expressionString;
	}

	public Position getPosition() {
		return position;
	}

	public String position() {
		return position.toString();
	}
}
